#include <iostream>
#include <sys/types.h>
#include <sys/msg.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

typedef struct
{
    long type; //类型
    int start; //消息队列本身
    int end;
} msg;

int main(int argc, char *argv[])
{

    if (argc < 2)
    {
        printf("usage:%s key\n", argv[0]);
        exit(1);
    }

    //获取key,这是指定的方式
    key_t key = atoi(argv[1]);
    //自动生成的方式
    //key_t key=IPC_PRIVATE;
    //通过函数生成key
   // key_t key=ftok(argv[1],0);//结合系统时间，生成一个key


    //创建消息队列
    int msq_id;
    if ((msq_id = msgget(key, IPC_CREAT | IPC_EXCL | 0777)) < 0)
    {
        std::cout << "msg failed" << std::endl;
        exit(1);
    }

    //定义要发送的消息

    msg m = {4, 4, 400}; // type  data data

    if (msgsnd(msq_id, &m, sizeof(msg) - sizeof(long), IPC_NOWAIT) < 0)
    {

        perror("msgsnd");
        exit(1);
    }

    //发送后获取消息队列中消息的总数
    struct msqid_ds ds;
    if (msgctl(msq_id, IPC_STAT, &ds) < 0)
    {
        perror("msq_id");
    }

    std::cout << ds.msg_qnum << std::endl;

    return 0;
}
